import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { title: '注册' }
  },
  {
    path: '/',
    component: () => import('../layout/index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'el-icon-s-home' }
      },
      {
        path: 'basic-info',
        name: 'BasicInfo',
        component: () => import('../views/basic-info/index.vue'),
        meta: { title: '高校基本信息', icon: 'el-icon-school' }
      },
      {
        path: 'majors',
        name: 'Majors',
        component: () => import('../views/majors/index.vue'),
        meta: { title: '学科与专业设置', icon: 'el-icon-reading' }
      },
      {
        path: 'faculty',
        name: 'Faculty',
        component: () => import('../views/faculty/index.vue'),
        meta: { title: '师资力量', icon: 'el-icon-user' }
      },
      {
        path: 'research',
        name: 'Research',
        component: () => import('../views/research/index.vue'),
        meta: { title: '科研实力', icon: 'el-icon-data-analysis' }
      },
      {
        path: 'campus-life',
        name: 'CampusLife',
        component: () => import('../views/campus-life/index.vue'),
        meta: { title: '校园生活', icon: 'el-icon-picture' }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('../views/users/index.vue'),
        meta: {
          title: '系统用户',
          icon: 'el-icon-user-solid',
          roles: ['1'] // 只允许角色值为 1 的管理员访问
        }
      },
      // {
      //   path: 'campus-life',
      //   name: 'CampusLife',
      //   component: () => import('../views/campus-life/index.vue'),
      //   meta: { title: '校园生活', icon: 'el-icon-picture' }
      // }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫：在每次路由跳转前进行检查，确保用户在未登录状态下无法访问除登录和注册页面之外的其他页面
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const userRole = localStorage.getItem('userRole')

  if (to.path === '/login' || to.path === '/register') {
    next()
  } else if (!token) {
    next('/login')
  } else {
    // 检查路由是否需要角色权限
    if (to.meta.roles) {
      // 检查用户角色是否满足要求
      if (to.meta.roles.includes(userRole)) {
        next()
      } else {
        next('/dashboard') // 无权限时重定向到首页
        Vue.prototype.$message.error('您没有权限访问该页面')
      }
    } else {
      next()
    }
  }
})

export default router
